package com.qf.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * author:z
 * time:2021/12/24 11:25
 * description:
 */
@RestController
public class TestController {

    //1. 准备商品的库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2. 准备商品的订单
    public static Map<String,Integer> itemOrder = new HashMap<>();

    static {
        itemStock.put("牙刷",1000);
        itemOrder.put("牙刷",0);
    }

    @Autowired
    CuratorFramework client;

    @RequestMapping("/kill")
    public String kill(String item) throws Exception {

        //创建zookeeper分布式锁
        InterProcessMutex lock=new InterProcessMutex(client,"/lock");
        try{
            if(lock.acquire(3, TimeUnit.SECONDS)){
                //减库存 判断是否有库存
                Integer stock = itemStock.get("牙刷");
                if(stock<=0){
                    return item+"卖完了====="+item+"还剩下:"+itemStock.get(item);
                }
                Thread.sleep(100);
                //库存减一
                itemStock.put(item,itemStock.get(item)-1);

                //增加订单
                Thread.sleep(100);
                itemOrder.put(item,itemOrder.get(item)+1);
                }
            }finally {
            //业务执行完场，则释放锁（删除创建的临时节点）
            lock.release();
        }
        return item+"还剩下"+itemStock.get(item)+"已卖"+item+":"+itemOrder.get(item);
    }
}
